package net.sevear.chaos.utils
{
	import com.douban.utils.Format;
	
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.utils.ByteArray;
	
	import net.sevear.chaos.download.Predef;
	

	public class Logger
	{
		private var HOST:String = "";
		private var repLoader:URLLoader;

		public function Logger()
		{
			this.log("Logger init, host =", Predef.CHAOS_HOST," ver =", Predef.VERSON);
			this.repLoader = new URLLoader();
			this.repLoader.addEventListener(IOErrorEvent.IO_ERROR, this.loader_ioError);
		}
		
		private static var instace:Logger;
		public static function getInstance():Logger{
			if(instace == null){
				instace = new Logger();
			}
			return instace;
		}
		
		public function log(kind:String,...args):void{
			var err:String = "";
			for each(var s:String in args){
				err += s+" ";
			}
			trace(kind,err);
			writeToLocalFile(err,kind);
		}
		
		public function logInfo(...args):void{
			var err:String = "";
			for each(var s:String in args){
				err += s+" ";
			}
			trace("Info:",err);
			writeToLocalFile(err,"Info:");
		}
		
		public function logError(...args):void{
			var err:String = "";
			for each(var s:String in args){
				err += s+" ";
			}
			trace("Error:",err);
			writeToLocalFile(err,"Error:");
		}
		
		public function report(re:String,kind:String):void{
			
		}
		
		private function loader_ioError(e:IOErrorEvent):void{
			log("report loader failed.");
		}
		
		private function writeToLocalFile(re:String,kind:String):void{
			var fl:File = File.applicationStorageDirectory.resolvePath("log.txt");
			var fs:FileStream = new FileStream();
			try{
				fs.open(fl,FileMode.APPEND);
				fs.writeUTFBytes(kind+" "+re+" "+Format.dateFormt(new Date())+"\n");
				fs.close();
			}catch(e:Error){
				trace("file operation error:",e.message);
			}
		}
	}
}